<template>
  <picker :value="value" @change="handleChange" @columnchange="handleColumnchange" mode="multiSelector"
          :range="pickerRange">
    <slot></slot>
  </picker>
</template>

<script>
import citys from './regions.json';

export default {
  name: 'CityPicker',
  props: {
    modelValue: {
      type: Array,
      default: () => [0, 0, 0]
    }
  },
  data() {
    return {
      title: 'Hello',
      citys,
      value: [0, 0, 0]
    }
  },
  watch: {
    modelValue: {
      handler(v) {
        const provinceIndex = this.citys.findIndex(province => province.name === v[0]) ?? 0;
        const province = this.citys[provinceIndex] ?? {};
        const cityIndex = province.childs?.findIndex?.(city => city.name === v[1]) ?? 0;
        const city = province.childs?.[cityIndex] ?? {};
        const distinctIndex = city.childs?.findIndex?.(distinct => distinct.name === v[2]) ?? 0;
        const value = [provinceIndex, cityIndex, distinctIndex];
        if (value.every(v => v !== -1)) {
          this.value = value;
        } else {
          console.warn('找不到城市');
        }
      },
      immediate: true
    }
  },
  computed: {
    selectProvince() {
      return this.citys[this.value[0]];
    },
    selectCity() {
      return this.selectProvince?.childs?.[this.value[1]];
    },
    selectDistinct() {
      return this.selectCity?.childs?.[this.value[2]];
    },
    pickerRange() {
      const province = this.citys;
      const city = this.selectProvince?.childs ?? [];
      const distinct = this.selectCity?.childs ?? [];
      return [
        province.map(child => child.name), city.map(child => child.name), distinct.map(child => child.name)
      ];
    }
  },
  onLoad() {
  },
  methods: {
    handleColumnchange(e) {
      const {
        detail: {
          column,
          value
        }
      } = e;
      const newValue = [...this.value];
      if (column === 0) {
        this.value = [value, 0, 0];
      } else if (column === 1) {
        this.value = [this.value[0], value, 0];
      } else {
        const newValue = this.value.slice(0, 2);
        newValue.push(value);
        this.value = newValue;
      }
    },
    handleChange(e) {
      const [p, c, d] = this.value;
      this.$emit('update:modelValue', [this.selectProvince?.name, this.selectCity?.name, this.selectDistinct?.name]);
    }
  }
}
</script>

<style>

</style>